package br.uneb.tebd.webservice;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import br.uneb.tebd.R;
import br.uneb.tebd.util.Constants;

public class CreateGuitarWS extends Activity {
	
	private Button register;
	private TextView description;
	private TextView model;
	private TextView brand;
	private WebServiceClient client;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.new_guitar);
		this.setTitle("Cadastrar Guitarra Externamente");
		
		this.client = new WebServiceClient();
		
		this.register = (Button) findViewById(R.id.registerButton);
		
		this.description = (TextView) findViewById(R.id.description);
		
		this.model = (TextView) findViewById(R.id.model);
		
		this.brand = (TextView) findViewById(R.id.brand);
		
		this.register.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (haveAnyBlankField() == false) {
					try {
						client.setDescription(description.getText().toString().trim());
						client.setMethod(WebServiceClient.FIND_BY_DESCRIPTION);
						client.Execute();
						if(client.getResponse().equalsIgnoreCase(Constants.MSG_GUITAR_NOT_FOUND)){
							client.setModel(model.getText().toString().trim());
							client.setBrand(brand.getText().toString().trim());
							client.setMethod(WebServiceClient.INSERT);
							client.Execute();
							clearFields();
							Toast.makeText(CreateGuitarWS.this, client.getResponse(), Toast.LENGTH_SHORT).show();
						} else{
							Toast.makeText(CreateGuitarWS.this, Constants.MSG_GUITAR_FOUND, Toast.LENGTH_SHORT).show();
						}
					} catch (Exception e) {
					    e.printStackTrace();
					}
				}
			}
		});
	}
	
	private void clearFields() {
		this.description.setText("");
		this.model.setText("");
		this.brand.setText("");
	}
	
	private boolean haveAnyBlankField() {
		
		boolean result = false;
		String description = this.description.getText().toString().trim();
		
		if (description.equals("")) {
			Toast.makeText(this, "É preciso preencher todos os campos.", Toast.LENGTH_SHORT).show();
			result = true;
		}
		
		String model = this.model.getText().toString().trim();
		
		if (model.equals("")) {
			Toast.makeText(this, "E preciso preencher todos os campos.", Toast.LENGTH_SHORT).show();
			result = true;
		}
		
		String brand = this.brand.getText().toString().trim();
		
		if (brand.equals("")) {
			Toast.makeText(this, "E preciso preencher todos os campos.", Toast.LENGTH_SHORT).show();
			result = true;
		}
		
		return result;
	}
	


}
